package com.letoy.study.config.auth;


import com.letoy.study.entity.AuthUser;
import com.letoy.study.entity.TokenInfo;
import com.letoy.study.service.TokenService;
import com.letoy.study.service.UserService;
import com.letoy.study.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 登录成功操作
 */
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Resource
    UserService userService;

    @Resource
    TokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //取得账号信息
        AuthUser authUser = (AuthUser) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        TokenInfo tokenInfo = tokenService.getTokenInfoByUserId(authUser.getId());
        tokenInfo.setUserId(authUser.getId());
        System.out.println(tokenInfo.toString());
        String systemToken = tokenInfo.getSystemToken();
        System.out.println("当前的token是：" + systemToken);

        if (systemToken == null) {
            systemToken = createNewToken(tokenInfo, authUser);
        } else {
            Boolean validate = false;
            if (!systemToken.equals("")){
                try {
                    validate = jwtTokenUtil.validateToken(systemToken, authUser);
                } catch (Exception e) {
                    System.out.println("验证token无效:" + e.getMessage());
                }
            }
            if (systemToken.equals("") | !validate) {
                systemToken = createNewToken(tokenInfo, authUser);
            }
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("username", authUser.getUsername());
        map.put("auth", authUser.getAuthorities());
        map.put("token", systemToken);
        //输出
        this.WriteJSON(request, response, map);

    }

    String createNewToken(TokenInfo tokenInfo, AuthUser authUser) {
        jwtTokenUtil = new JwtTokenUtil();
        String systemToken = jwtTokenUtil.generateToken(authUser);
        //把新的token存储到缓存中
        tokenInfo.setSystemToken(systemToken);
        tokenService.updateTokenInfo(tokenInfo);
        return systemToken;
    }
}
